<?php

namespace app\system\controller;

use app\common\model\ConfigModel;
use app\common\model\DictModel;
use helper\TpConfig;

class ConfigController extends BaseController
{

  /**
   * 不需要登陆的方法
   * @var array
   */
  protected $noLogin = [];

  /**
   * 不检测权限方法
   * @var array
   */
  protected $noCheck = [];

  /**
   * 权限映射
   * @var array
   */
  protected $mapCheck = [
    '*' => 'index'
  ];

  /**
   * 当前模型
   * @var null
   */
  protected $model = null;

  /**
   * 初始化
   */
  public function __construct()
  {
    parent::__construct();
    $this->model = new ConfigModel();
  }

  /**
   * 配置首页
   * @return array|string
   * @throws \Exception
   */
  public function index()
  {
    if ($this->request->isAjax()) {
      $config   = $this->request->param('config/a');
      $dataList = [];
      foreach ($config as $key => $value) {
        $info = $this->model->where('config_key', $key)->find();
        if ($info['config_type'] == '_switch') {
          $value = isset($config[$info[$key]]) ? 1 : 0;
        }
        if ($info['config_type'] == '_switch') $value = isset($config[$info[$key]]) ? 1 : 0;
        if ($info['config_type'] == '_checkbox') $value = isset($config[$info[$key]])
          ? explode(',', $config[$info[$key]])
          : '';
        if ($info) {
          $dataList[] = ['id' => $info['id'], 'config_key' => $key, 'config_value' => $value];
        } else {
          $dataList[] = ['config_key' => $key, 'config_value' => $value];
        }
      }
      $this->model->saveAll($dataList);
      $this->model->refreshCache();
      $this->success('操作成功');
    }
    $groupList = $this->getGroupList();
    $group     = $this->request->param('group', 'site');
    $formList  = $this->model->getForm($group);
    $this->assign('form_list', $formList);
    $this->assign('group', $group);
    $this->assign('group_list', $groupList);
    return $this->fetch();
  }

  /**
   * 添加配置项
   * @return string
   * @throws \Exception
   */
  public function add()
  {
    if ($this->request->isAjax()) {
      $data = $this->request->param();
      $this->validate($data, [
        'config_group|字段分组' => 'require',
        'config_type|字段类型'  => 'require',
        'config_key|字段标识'   => 'require',
        'config_title|字段标题' => 'require'
      ]);
      $this->model->add($data);
      $this->model->refreshCache();
      $this->success('操作成功');
    }
    $configType = [
      ["key" => "_text", "name" => '文本框'],
      ["key" => "_password", "name" => '密码框'],
      ["key" => "_laydate", "name" => '日期框'],
      ["key" => "_number", "name" => '数字框'],
      ["key" => "_textarea", "name" => '多行文本框'],
      ["key" => "_switch", "name" => 'switch选项'],
      ["key" => "_tags", "name" => 'tags选择'],
      ["key" => "_area", "name" => '省市区选择'],
      ["key" => "_select", "name" => '下拉框'],
      ["key" => "_checkbox", "name" => '多选框'],
      ["key" => "_radio", "name" => '单选框'],
      ["key" => "_selectPage", "name" => 'selectPage选择框'],
      ["key" => "_uploadImage", "name" => '图片上传'],
    ];
    $this->assign('config_type', $configType);
    return $this->fetch();
  }

  /**
   * 修改配置
   * @throws \Exception
   */
  public function edit()
  {
    if ($this->request->isAjax()) {
      $data = $this->request->param();
      $this->validate($data, [
        'config_title|字段标题' => 'require'
      ]);
      $this->model->edit($data);
      $this->model->refreshCache();
      $this->success('操作成功');
    }
    $id   = $this->request->param('id/d');
    $info = $this->model->getById($id);
    $this->assign('info', $info);
    return $this->fetch();
  }

  /**
   * 上传配置
   * @return string
   * @throws \Exception
   */
  public function upload()
  {
    $config = config('filesystem');
    if ($this->request->isAjax()) {
      $data = $this->request->param();
      if (empty($data['default'])) abort(500, '上传驱动不能为空');
      $default                   = $data['default'];
      $config['default']         = $default;
      $uploadConfig              = array_merge($config['disks'][$default], $data['disks'][$default]);
      $config['disks'][$default] = $uploadConfig;
      TpConfig::write('filesystem', $config);
      $this->success('操作成功');
    }
    $this->assign('group_list', $this->getGroupList());
    $this->assign('config', $config);
    return $this->fetch();
  }

  /**
   * 短信配置
   * @return string
   * @throws \Exception
   */
  public function sms()
  {
    $config = config('sms');
    if ($this->request->isAjax()) {
      $data = $this->request->param();
      if (empty($data['default']['gateways'])) abort(500, '默认发送接口不能为空');
      $defaultGateways                      = $data['default']['gateways'];
      $config['default']['gateways']        = [$defaultGateways]; //默认网关
      $gatewaysConfig                       = array_merge($config['gateways'][$defaultGateways], $data['gateways'][$defaultGateways]);
      $config['gateways'][$defaultGateways] = $gatewaysConfig;
      TpConfig::write('sms', $config);
      $this->success('操作成功');
    }
    $config['default']['gateways'] = implode(',', $config['default']['gateways']);
    $this->assign('group_list', $this->getGroupList());
    $this->assign('config', $config);
    return $this->fetch();
  }

  /**
   * 获取分组类别
   * @return \think\Collection
   * @throws \Exception
   */
  private function getGroupList()
  {
    return DictModel::where('class_code', '10.15')->order('show_order asc')->select();
  }

  /**
   * 刷新缓存
   */
  public function refresh()
  {
    $this->model->refreshCache();
    $this->success('操作成功');
  }

  /**
   * 删除配置
   * @throws \Exception
   */
  public function del()
  {
    $id = $this->request->param('id/d');
    $this->model->del($id);
    $this->success('操作成功');
  }
}
